package com.data.sample.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class KafkaProducerService {

    private final KafkaTemplate<String, Object> kafkaTemplate;

    public KafkaProducerService(KafkaTemplate<String, Object> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    /**
     * 发送单个对象到 Kafka - 方式1：使用 ListenableFuture
     */
    public void sendObject(String topic, Object data) {
        // 方法1：使用 addCallback（推荐）
        kafkaTemplate.send(topic, data).addCallback(
                result -> {
                    // 成功回调
                    System.out.println("kafka发送成功");
                },
                ex -> {
                    // 失败回调
                    System.out.println("kafka发送失败");;
                }
        );
    }
}